package com.mblog.article.controller;


import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mblog.article.entity.MBlogMain;
import com.mblog.article.entity.MBlogType;
import com.mblog.article.service.ArticleService;
import com.mblog.article.service.ArticleTypeService;
import com.mblog.util.FileUpload;
import com.mblog.util.PageBean;
import com.mblog.util.PageHelper.Page;
import com.mblog.util.PageHelper.PageImpl;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/")
public class ArticleController{
	
	@Autowired
	private ArticleService articleService;
	
	@Autowired
	private ArticleTypeService articleTypeService;
	
	static int pageSize=8;

	//文章列表
	@RequestMapping(value="/goArticleList.do")
	public  String goArticleList(HttpServletResponse responese,HttpServletRequest request){
		try {
			String pageNos=request.getParameter("currentPage");
			if(pageNos==null||"".equals(pageNos)){
				pageNos="1";
			}
			int pageNo=Integer.parseInt(pageNos);
			Map<String,Object> map=new HashMap<String,Object>();
			String searchTitle=request.getParameter("searchTitle");
			if(searchTitle!=null&&!"".equals(pageNos)){
				map.put("title", searchTitle);
			}			
			PageBean page=articleService.selectAllArticleByPage(pageNo, pageSize, map);
			@SuppressWarnings("unchecked")
			List<MBlogMain> lists=(List<MBlogMain>)page.getResult();
			//获取文章分类列表
			List<MBlogType> mblogType=articleTypeService.selectAll();
			for (int i = 0; i < lists.size(); i++) {
				String content=lists.get(i).getContent();
				if(content!=null&&!"".equals(content)){
				content=content.replaceAll("<[^\\>]*>","");
				content=content.replaceAll("\\&[a-zA-Z]{1,10};", "");
				lists.get(i).setContent(content.trim());
				}
			}
			//获取所有文章标签
			List<MBlogMain> tags=articleService.selectAllArticleTags();
			Set<String> set = new HashSet<String>();  
			for (int i = 0; i < tags.size(); i++) {
				String[] keywords=tags.get(i).getKeyword().split(",");
			    for(int j = 0; j < keywords.length ; j++){  
			        set.add(keywords[j]);  
			    }  
			}

			request.setAttribute("Page", page);
			request.setAttribute("currentPage", pageNo);
			request.setAttribute("searchTitle", searchTitle);
			request.setAttribute("mblogType", mblogType);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "back/index";
	}
	//添加文章
	@RequestMapping(value="/goAddArticleInfo.do")
	public  String goAddArticleInfo(HttpServletResponse response,HttpServletRequest request,@ModelAttribute MBlogMain article){
		try {
			article.setReleasedate(new Date());
			articleService.insert(article);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/goArticleList.do";
	}
	//添加文章图片上传
	@RequestMapping(value="/uploadArticleImg.do")
	@ResponseBody
	public  String uploadArticleImg(@RequestParam("articleimg")MultipartFile file,HttpServletRequest request){
			JSONObject json= new JSONObject();
			String s="";
			try {
					 if (!file.isEmpty()) {
						  String uploadPath=request.getServletContext().getRealPath("/") ;
						  String fileName=FileUpload.saveUploadFile(file,uploadPath+"/upload/");
						  json.put("original", fileName);
						  json.put("name", fileName);
						  s="{\"name\":\""+  fileName+"\", \"originalName\": \""+ fileName +"\", \"size\": "+ file.getSize() +", \"state\": \"SUCCESS\", \"type\": \""+fileName.substring(fileName.lastIndexOf("."))+"\", \"url\": \""+fileName+ "\"}";
						  s = s.replaceAll( "\\\\", "\\\\" );
					  }
			} catch (Exception e) {
				e.printStackTrace();
			}
			return s;
					
	}

	//获取文章
	@RequestMapping(value="/searchArticleInfo.do")
	@ResponseBody
	public String searchArticleInfo(HttpServletRequest request,String articleid){
		JSONObject json=new JSONObject();
		MBlogMain  mblog=new MBlogMain();
		try {
			mblog=articleService.selectByPrimaryKey(Integer.parseInt(articleid));
			json.put("articlevo", mblog);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
	}
	//编辑文章
	@RequestMapping(value="/goUpdateArticleInfo.do")
	public  String goUpdateArticleInfo(HttpServletResponse response,HttpServletRequest request,@ModelAttribute MBlogMain article){
		try {
			articleService.updateByPrimaryKey(article);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/goArticleList.do";
	}	
	//删除文章
	@RequestMapping(value="/goDeleteArticleInfo.do")
	public  String goDeleteArticleInfo(HttpServletResponse response,HttpServletRequest request,String ids){
		try {
			String[] idsArray=new String[]{};
			if(ids!=null&&!"".equals(ids)){
				idsArray=ids.split(",");
			}
			for (int i = 0; i < idsArray.length; i++) {
				articleService.deleteByPrimaryKey(Integer.parseInt(idsArray[i]));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/goArticleList.do";
	}	
	


}